<template>
<div class="modal" ref="dlg" data-backdrop="static" data-disable="false" data-keyboard="true" tabindex="-1">
    <div :class="['modal-dialog', {'modal-lgg': bShowMore, 'modal-lg': !bShowMore}]">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title text-center">通道配置({{ChannelInfo.Channel}})</h4>
            </div>
            <form class="form-horizontal" @submit.prevent="submit" autocomplete="off" spellcheck="false">
                <div class="modal-body">
                    <div :class="[{'col-md-6': bShowMore, 'col-md-12': !bShowMore}]">
                        <div :class="['form-group' , {'has-error': errors.has('Name')}]">
                            <label for="input-name" class="col-sm-4 control-label">
                                通道名称
                                <span class="text-red">*</span>
                            </label>
                            <div class="col-sm-7">
                                <input id="input-name" type="text" class="form-control" name="Name" v-model.trim="ChannelInfo.Name" data-vv-as="通道名称">
                            </div>
                        </div>
                        <input id="input-channel" type="hidden"  name="Channel" class="form-control"  readonly="readonly" v-model="ChannelInfo.Channel">
                        <div class="form-group">
                            <label for="input-protocol" class="col-sm-4 control-label">
                                直播流接入类型
                            </label>
                            <div class="col-sm-7">
                                <div class="input-group" v-if="ChannelInfo.Protocol == 'ONVIF' || ChannelInfo.Protocol == 'RTSP'">
                                    <select id="input-protocol" name="Protocol" class="form-control" v-model="ChannelInfo.Protocol">
                                        <option value="RTSP" selected="selected">RTSP</option>
                                        <option value="ONVIF">ONVIF</option>
                                        <option value="RTMP">RTMP</option>
                                        <option value="FLV">FLV</option>
                                        <option value="HLS">HLS</option>
                                        <option value="FILE">视频文件</option>
                                        <option value="ISUP">海康 ISUP</option>
                                        <option value="HIKSDK">海康 SDK</option>
                                        <option value="DHSDK">大华 SDK</option>
                                        <option value="TDYSDK">天地伟业 SDK</option>
                                    </select>
                                    <span class="input-group-addon">
                                        <el-checkbox v-model="detect" class="no-margin">ONVIF 探测</el-checkbox>
                                    </span>
                                </div>
                                <select id="input-protocol" name="Protocol" class="form-control" v-model="ChannelInfo.Protocol" v-else>
                                    <option value="RTSP" selected="selected">RTSP</option>
                                    <option value="ONVIF">ONVIF</option>
                                    <option value="RTMP">RTMP</option>
                                    <option value="FLV">FLV</option>
                                    <option value="HLS">HLS</option>
                                    <option value="FILE">视频文件</option>
                                    <option value="ISUP">海康 ISUP</option>
                                    <option value="HIKSDK">海康 SDK</option>
                                    <option value="DHSDK">大华 SDK</option>
                                    <option value="TDYSDK">天地伟业 SDK</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group" v-show="(ChannelInfo.Protocol == 'ONVIF' || ChannelInfo.Protocol == 'RTSP') && detect">
                            <label for="input-onvif-ip" class="col-sm-4 control-label">
                                探测ONVIF IP
                                <span class="text-red">*</span>
                            </label>
                            <div class="col-sm-7">
                                <el-autocomplete id="input-onvif-ip" style="width: 100%" v-model.trim="detectIP" :fetch-suggestions="discover" placeholder="请输入探测IP"></el-autocomplete>
                            </div>
                        </div>
                        <div class="form-group" v-show="(ChannelInfo.Protocol == 'ONVIF' || ChannelInfo.Protocol == 'RTSP') && detect">
                            <label for="input-onvif-username" class="col-sm-4 control-label">
                                探测ONVIF用户名
                            </label>
                            <div class="col-sm-7">
                                <input id="input-onvif-username" type="text" class="form-control" name="detectUsername" v-model.trim="detectUsername">
                            </div>
                        </div>
                        <div class="form-group" v-show="(ChannelInfo.Protocol == 'ONVIF' || ChannelInfo.Protocol == 'RTSP') && detect">
                            <label for="input-onvif-password" class="col-sm-4 control-label">
                                探测ONVIF密码
                            </label>
                            <div class="col-sm-7">
                                <div class="input-group">
                                    <input id="input-onvif-password" type="text" class="form-control" name="detectPassword" v-model.trim="detectPassword" v-if="rawDetectPwd">
                                    <input id="input-onvif-password" type="password" class="form-control" name="detectPassword" autocomplete="new-password" v-model.trim="detectPassword" v-else
                                        onfocus="this.readOnly = false;" onblur="this.readOnly = true;" style="background-color: #FFF;" readonly>
                                    <span class="input-group-btn">
                                        <button type="button" class="btn btn-default" @click="rawDetectPwd = !rawDetectPwd;" style="border-top-right-radius:0;border-bottom-right-radius:0;">
                                            <i class="glyphicon glyphicon-eye-open" v-if="rawDetectPwd"></i>
                                            <i class="glyphicon glyphicon-eye-close" v-else></i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group" v-show="(ChannelInfo.Protocol == 'ONVIF' || ChannelInfo.Protocol == 'RTSP') && detect">
                            <div class="col-sm-7 col-sm-offset-4">
                                <button class="btn btn-primary" type="button" @click.prevent="probe">探测</button>
                            </div>
                        </div>
                        <div class="form-group" v-show="ChannelInfo.Protocol == 'ONVIF'">
                            <label for="input-onvif" class="col-sm-4 control-label">
                                摄像机接入ONVIF地址
                            </label>
                            <div class="col-sm-7">
                                <input id="input-onvif" type="text" class="form-control" name="Onvif" v-model.trim="ChannelInfo.Onvif">
                            </div>
                        </div>
                        <div class="form-group" v-if="ChannelInfo.Protocol.endsWith('SDK')">
                            <label for="input-sdk-ip" class="col-sm-4 control-label">
                                {{ sdkText }} IP 端口
                                <span class="text-red">*</span>
                            </label>
                            <div :class="['col-sm-4', {'has-error': errors.has('sdkIP')}]">
                                <input id="input-sdk-ip" type="text" class="form-control" name="sdkIP" v-model.trim="sdkIP" placeholder="IP" data-vv-as="IP" v-validate="'required|url'">
                                <span class="help-block visible-xs-block"></span>
                            </div>
                            <div :class="['col-sm-3', {'has-error': errors.has('sdkPort')}]">
                                <input id="input-sdk-port" type="text" class="form-control" name="sdkPort" v-model.trim="sdkPort" placeholder="端口" data-vv-as="端口" v-validate="'required|numeric|min_value:1|max_value:65535'">
                            </div>
                        </div>
                        <div class="form-group" v-if="ChannelInfo.Protocol.endsWith('SDK')">
                            <label for="input-sdk-channel" class="col-sm-4 control-label">
                                {{ sdkText }} 通道
                            </label>
                            <div :class="['col-sm-4', {'has-error': errors.has('sdkChannel')}]">
                                <input id="input-sdk-channel" type="text" class="form-control" name="sdkChannel" v-model.trim="sdkChannel" placeholder="通道" data-vv-as="通道" v-validate="'required|numeric|min_value:1'">
                                <span class="help-block visible-xs-block"></span>
                            </div>
                            <div :class="['col-sm-3', {'has-error': errors.has('sdkStreamType')}]">
                                <select id="input-sdk-stream-type" name="sdkStreamType" class="form-control" v-model.trim="sdkStreamType" data-vv-as="码流类型" v-validate="'numeric|min_value:0'">
                                    <option value="0" selected="selected">主码流</option>
                                    <option value="1">子码流</option>
                                    <option value="2">三码流</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group" v-if="ChannelInfo.Protocol == 'ISUP'">
                            <label for="input-isup-device-id" class="col-sm-4 control-label">
                                海康 ISUP 设备ID
                                <span class="text-red">*</span>
                            </label>
                            <div :class="['col-sm-7', {'has-error': errors.has('isupDeviceID')}]">
                                <el-autocomplete id="input-isup-device-id" name="isupDeviceID" style="width: 100%" v-model.trim="isupDeviceID" :fetch-suggestions="isupDevices" placeholder="设备ID" data-vv-as="设备ID" v-validate="'required'">
                                    <template slot-scope="{ item }">
                                        <div>{{ item.value }} ({{ item.ip }})</div>
                                    </template>
                                </el-autocomplete>
                            </div>
                        </div>
                        <div class="form-group" v-if="ChannelInfo.Protocol == 'ISUP'">
                            <label for="input-isup-channel" class="col-sm-4 control-label">
                                海康 ISUP 通道
                            </label>
                            <div :class="['col-sm-4', {'has-error': errors.has('isupChannel')}]">
                                <el-autocomplete id="input-isup-channel" name="isupChannel" style="width: 100%" v-model.trim="isupChannel" :fetch-suggestions="isupChannels" placeholder="通道" data-vv-as="通道" v-validate="'required|numeric|min_value:1'">
                                </el-autocomplete>
                                <span class="help-block visible-xs-block"></span>
                            </div>
                            <div :class="['col-sm-3', {'has-error': errors.has('isupStreamType')}]">
                                <select id="input-isup-stream-type" name="isupStreamType" class="form-control" v-model.trim="isupStreamType" data-vv-as="码流类型" v-validate="'numeric|min_value:0'">
                                    <option value="0" selected="selected">主码流</option>
                                    <option value="1">子码流</option>
                                    <option value="2">三码流</option>
                                </select>
                            </div>
                        </div>
                        <div :class="['form-group' , {'has-error': errors.has('Rtsp')}]" title="支持RTSP、RTMP、FLV、HLS等直播源地址配置" v-if="!ChannelInfo.Protocol.endsWith('SDK') && ChannelInfo.Protocol != 'ISUP'">
                            <label for="input-rtsp" class="col-sm-4 control-label">
                                {{ rtspText }}
                            </label>
                            <div class="col-sm-7">
                                <input id="input-rtsp" type="text" class="form-control" name="Rtsp" v-model.trim="ChannelInfo.Rtsp">
                            </div>
                        </div>
                        <div class="form-group" v-show="showAuth">
                            <label for="input-username" class="col-sm-4 control-label">
                                摄像机用户名
                            </label>
                            <div class="col-sm-7">
                                <input id="input-username" type="text" class="form-control" name="UserName" v-model.trim="ChannelInfo.UserName">
                            </div>
                        </div>
                        <div class="form-group" v-show="showAuth">
                            <label for="input-password" class="col-sm-4 control-label">
                                摄像机密码
                            </label>
                            <div class="col-sm-7">
                                <div class="input-group">
                                    <input id="input-password" type="text" class="form-control" name="Password" v-model.trim="ChannelInfo.Password" v-if="rawCameraPwd">
                                    <input id="input-password" type="password" class="form-control" name="Password" autocomplete="new-password" v-model.trim="ChannelInfo.Password" v-else
                                        onfocus="this.readOnly = false;" onblur="this.readOnly = true;" style="background-color: #FFF;" readonly>
                                    <span class="input-group-btn">
                                        <button type="button" class="btn btn-default" @click="rawCameraPwd = !rawCameraPwd;" style="border-top-right-radius:0;border-bottom-right-radius:0;">
                                            <i class="glyphicon glyphicon-eye-open" v-if="rawCameraPwd"></i>
                                            <i class="glyphicon glyphicon-eye-close" v-else></i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group" title="不填表示当前通道不作国标级联">
                            <label for="input-gbid" class="col-sm-4 control-label">
                                国标编号
                            </label>
                            <div class="col-sm-7">
                                <input id="input-gbid" type="text" class="form-control" name="GBID" v-model.trim="ChannelInfo.GBID" placeholder="可选 不填表示不作国标级联">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="input-audio" class="col-sm-4 control-label">
                                音频输出
                            </label>
                            <div class="col-sm-7" v-loading="bAudioUploading">
                                <div class="input-group">
                                    <div class="input-group-btn">
                                        <button id="input-audio-dropdown" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-top-left-radius:0;border-bottom-left-radius:0;">
                                            {{audioText}} <span class="caret"></span>
                                        </button>
                                        <ul id="input-audio-menu" class="dropdown-menu">
                                            <li><a href="#" data-audio="0">静音</a></li>
                                            <li><a href="#" data-audio="1">原始音频</a></li>
                                            <!-- <li role="separator" class="divider"></li> -->
                                            <li><a href="#">自定义音频</a></li>
                                        </ul>
                                    </div><!-- /btn-group -->
                                    <el-autocomplete id="input-audio" style="width: 100%;" v-model.trim="ChannelInfo.Audio"  :fetch-suggestions="listAudio" v-show="!audioReadonly" placeholder="音频资源链接"></el-autocomplete>
                                    <!-- <input id="input-audio" type="text" class="form-control" aria-label="custom audio" v-model.trim="ChannelInfo.Audio" v-show="!audioReadonly" placeholder="音频资源链接"> -->
                                </div><!-- /input-group -->
                                <span class="help-block" v-show="!audioReadonly">
                                    <el-upload drag action="/api/v1/audio/upload" accept=".mp4,.mp3,.wav,.ps,.ts,.avi,.mkv"
                                        :show-file-list="false"
                                        :on-success="onUploadAudioSuccess" :on-error="onUploadAudioError" :on-progress="onUploadAudioProgress"
                                        ref="audio-uploader" id="audio-uploader">
                                        <i class="el-icon-upload"></i>
                                        <div class="el-upload__text">将音频资源拖到此处，或 <em>点击上传</em><br></div>
                                    </el-upload>
                                </span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="input-transport" class="col-sm-4 control-label">
                                传输协议
                            </label>
                            <div class="col-sm-7">
                                <el-radio-group id="input-transport" v-model.trim="ChannelInfo.Transport" size="mini">
                                    <el-radio-button label="TCP"></el-radio-button>
                                    <el-radio-button label="UDP"></el-radio-button>
                                    <el-radio-button label="Multicast"></el-radio-button>
                                </el-radio-group>
                            </div>
                        </div>
                        <div class="form-group" v-if="serverInfo.VersionType != '标准版'" title="-1(永久保存), 0(关闭录像), x>0(录像保存x天)">
                            <label for="input-record" class="col-sm-4 control-label">
                                录像保留(天)
                            </label>
                            <div class="col-sm-7">
                                <el-input-number id="input-record" v-model.number="ChannelInfo.Record" :min="-1" :max="1000" size="small"></el-input-number>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="input-ondemand" class="col-sm-4 control-label">
                                其他选项
                            </label>
                            <div class="col-sm-7 checkbox">
                                <el-checkbox id="input-enable" size="small" style="margin-left:-19px;margin-top:-5px;" v-model.trim="ChannelInfo.Enable" :true-label="1" :false-label="0">
                                    是否启用&nbsp;&nbsp;&nbsp;&nbsp;
                                </el-checkbox>
                                <el-checkbox id="input-ondemand" size="small" style="margin-left:-19px;margin-top:-5px;" v-model.trim="ChannelInfo.OnDemand" :true-label="1" :false-label="0" title="开启按需直播后，仅在有人观看时取流，以节省网络资源">
                                    按需直播&nbsp;&nbsp;&nbsp;&nbsp;
                                </el-checkbox>
                                <a href="#" class="form-control-static text-primary" @click.prevent="bShowMore = true;" v-show="!bShowMore">
                                    显示更多配置 &gt;&gt;
                                </a>
                                <!-- <el-checkbox id="input-show-more" size="small" style="margin-left:-19px;margin-top:-5px;" v-model.trim="bShowMore">更多配置</el-checkbox> -->
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6" v-if="bShowMore">
                        <div class="form-group">
                            <label for="input-cdn" class="col-sm-4 control-label">
                                转推CDN地址
                            </label>
                            <div class="col-sm-7">
                                <input id="input-cdn" type="text" class="form-control" name="Cdn" v-model.trim="ChannelInfo.Cdn" placeholder="可选 配置 rtsp 或 rtmp 推流地址">
                            </div>
                        </div>
                        <div class="form-group" title="视频叠加显示的水印">
                            <label for="input-osd" class="col-sm-4 control-label">
                                叠加水印
                            </label>
                            <div class="col-sm-7">
                                <el-input id="input-osd" type="textarea" v-model.trim="ChannelInfo.OSD" :autosize="{minRows:1, maxRows:10}" :rows="1" placeholder="可选 配置视频上叠加水印"></el-input>
                                <!-- <input id="input-osd" type="text" class="form-control" name="OSD" v-model.trim="ChannelInfo.OSD" placeholder="可选 配置视频上叠加水印"> -->
                            </div>
                        </div>
                       <div :class="['form-group', {'has-error': errors.has('Longitude')}]">
                            <label for="input-longitude" class="col-sm-4 control-label">
                                经度
                            </label>
                            <div class="col-sm-7">
                                <input id="input-longitude" type="text" class="form-control" name="Longitude" v-model.trim="ChannelInfo.Longitude"
                                    @paste="onPasteLngLat"
                                    placeholder="可选" data-vv-as="经度" v-validate="'decimal'">
                            </div>
                        </div>
                        <div :class="['form-group', {'has-error': errors.has('Latitude')}]">
                            <label for="input-latitude" class="col-sm-4 control-label">
                                纬度
                            </label>
                            <div class="col-sm-7">
                                <input id="input-latitude" type="text" class="form-control" name="Latitude" v-model.trim="ChannelInfo.Latitude"
                                    @paste="onPasteLngLat"
                                    placeholder="可选" data-vv-as="纬度" v-validate="'decimal'">
                            </div>
                        </div>
                        <div :class="['form-group', {'has-error': errors.has('RequireVideoWidth')}]" title="涉及视频转码，请谨慎配置！">
                            <label for="input-video-width" class="col-sm-4 control-label">
                                视频宽
                            </label>
                            <div class="col-sm-7">
                                <input id="input-video-width" type="text" class="form-control" name="RequireVideoWidth" v-model.trim="ChannelInfo.RequireVideoWidth" placeholder="可选 配置分辨率宽" data-vv-as="视频宽" v-validate="'numeric|min_value:1'">
                            </div>
                        </div>
                        <div :class="['form-group', {'has-error': errors.has('RequireVideoHeight')}]" title="涉及视频转码，请谨慎配置！">
                            <label for="input-video-height" class="col-sm-4 control-label">
                                视频高
                            </label>
                            <div class="col-sm-7">
                                <input id="input-video-height" type="text" class="form-control" name="RequireVideoHeight" v-model.trim="ChannelInfo.RequireVideoHeight" placeholder="可选 配置分辨率高" data-vv-as="视频高" v-validate="'numeric|min_value:1'">
                            </div>
                        </div>
                        <div :class="['form-group', {'has-error': errors.has('RequireVideoBitRate')}]" title="涉及视频转码，请谨慎配置！">
                            <label for="input-bitrate" class="col-sm-4 control-label">
                                视频码率
                            </label>
                            <div class="col-sm-7">
                                <input id="input-bitrate" type="text" class="form-control" name="RequireVideoBitRate" v-model.trim="ChannelInfo.RequireVideoBitRate" placeholder="可选 配置码率 Kbps" data-vv-as="视频码率" v-validate="'numeric|min_value:1'">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="input-description" class="col-sm-4 control-label">
                                备注
                            </label>
                            <div class="col-sm-7">
                                <el-input id="input-description" type="textarea" v-model.trim="ChannelInfo.Description" :autosize="{minRows:3, maxRows:5}" :rows="3" placeholder="可选"></el-input>
                                <!-- <input id="input-description" type="text" class="form-control" name="Description" v-model.trim="ChannelInfo.Description" placeholder="可选"> -->
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-4 control-label"></label>
                            <div class="col-sm-7">
                                <a href="#" class="form-control-static text-primary" @click.prevent="bShowMore = false;" v-show="bShowMore">&lt;&lt; 关闭更多配置</a>
                            </div>
                        </div>
                    </div>
                    <div class="clearfix"></div>
                </div>
                <div class="modal-footer">
                    <div class="inline text-orange" v-if="alertMsg">
                        <small>
                            <strong><i class="fa fa-info-circle"></i> 提示 : &nbsp;&nbsp;</strong>
                            {{alertMsg}}
                            &nbsp;&nbsp;
                        </small>
                    </div>
                    <button type="button" class="btn btn-default" data-dismiss="modal" :disabled="bAudioUploading">取消</button>
                    <button type="submit" class="btn btn-primary" :disabled="errors.any() || isNoChange || bAudioUploading">确定</button>
                </div>
            </form>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
</template>

<script>
import url from 'url';
import { mapState, mapActions } from "vuex";
export default {
    data() {
        return {
            ChannelInfo: this.defChannelInfo(),
            origData: "",
            detect: false,
            detectIP: "",
            detectUsername: "",
            detectPassword: "",

            sdkIP: "",
            sdkPort: "",
            sdkChannel: 1,
            sdkStreamType: 0,

            isupDeviceID: "",
            isupChannel: '1',
            isupStreamType: 0,
            isupEnable: false,
            isupListen: false,
            isupStatus: "",
            isupOnlineCount: 0,

            audioBak: "",
            bAudioUploading: false,
            rawDetectPwd: true,
            rawCameraPwd: true,
            bShowMore: false,
            bShow: false,
        };
    },
    mounted() {
        var vm = this;
        $(this.$el).on("hide.bs.modal", () => {
            this.bShow = false;
            this.ChannelInfo = this.defChannelInfo();
            this.detect = false;
            this.detectIP = "";
            this.detectUsername = "";
            this.detectPassword = "";

            this.sdkIP = "";
            this.sdkPort = "";
            this.sdkChannel = 1;
            this.sdkStreamType = 0;

            this.isupDeviceID = "";
            this.isupChannel = '1';
            this.isupStreamType = 0;
            this.isupEnable = false;
            this.isupListen = false;
            this.isupStatus = "";
            this.isupOnlineCount = 0;

            this.audioBak = "";
            this.bAudioUploading = false;
        }).on("shown.bs.modal", () => {
            this.bShow = true;
            this.rawDetectPwd = false;
            this.rawCameraPwd = false;
        }).on("click", "#input-audio-menu a", function() {
            var val = $(this).attr("data-audio");
            if(val) {
                var audio = vm.ChannelInfo["Audio"];
                if (audio != "0" && audio != "1") {
                    vm.audioBak = audio;
                }
                vm.ChannelInfo["Audio"] = val;
            } else {
                vm.ChannelInfo["Audio"] = vm.audioBak;
                vm.$nextTick(() => {
                    $(vm.$el).find("#input-audio").focus();
                })
            }
        });
    },
    methods: {
        show(data) {
            this.rawDetectPwd = true;
            this.rawCameraPwd = true;
            Object.assign(this.ChannelInfo, data || {});
            this.ChannelInfo.Longitude = data.Longitude || "";
            this.ChannelInfo.Latitude = data.Latitude || "";
            this.ChannelInfo.RequireVideoBitRate = data.RequireVideoBitRate || "";
            this.ChannelInfo.RequireVideoWidth = data.RequireVideoWidth || "";
            this.ChannelInfo.RequireVideoHeight = data.RequireVideoHeight || "";
            if(this.ChannelInfo.Protocol.endsWith("SDK") && this.ChannelInfo.Rtsp) {
                var u = url.parse(this.ChannelInfo.Rtsp, true);
                this.sdkIP = u.hostname || "";
                this.sdkPort = u.port || this.defSdkPort(this.ChannelInfo.Protocol);
                if(u.pathname && u.pathname.startsWith("/")) {
                    var channel = parseInt(u.pathname.substr(1));
                    if(!isNaN(channel) && channel > 0) {
                        this.sdkChannel = channel;
                    }
                }
                if(u.query['streamType']) {
                    var stream = parseInt(u.query['streamType']);
                    if(!isNaN(stream) && stream >= 0){
                        this.sdkStreamType = stream;
                    }
                }
                this.ChannelInfo.Rtsp = "";
            }
            if(this.ChannelInfo.Protocol == "ISUP" && this.ChannelInfo.Rtsp) {
                var u = url.parse(this.ChannelInfo.Rtsp, true);
                if(u.pathname && u.pathname.startsWith("/")) {
                    var channel = parseInt(u.pathname.substr(1));
                    if(!isNaN(channel) && channel > 0) {
                        this.isupChannel = `${channel}`;
                    }
                }
                if(u.query['deviceID']) {
                    this.isupDeviceID = u.query['deviceID'];
                }
                if(u.query['streamType']) {
                    var stream = parseInt(u.query['streamType']);
                    if(!isNaN(stream) && stream >= 0){
                        this.isupStreamType = stream;
                    }
                }
                this.ChannelInfo.Rtsp = "";
            }
            this.origData = JSON.stringify(this.getCommitData());
            setTimeout(() => {
                $(this.$refs["dlg"]).modal("show");
            }, 100);
        },
        hide() {
            $(this.$refs["dlg"]).modal("hide");
        },
        async submit() {
            var ok = await this.$validator.validateAll();
            if(!ok) {
                var e = this.errors.items[0];
                this.$message({
                    type: 'error',
                    message: e.msg
                })
                $(`[name=${e.field}]`).focus();
                return;
            }
            if(this.ChannelInfo.Protocol.endsWith("SDK")) {
                this.ChannelInfo.Rtsp = `${this.ChannelInfo.Protocol.toLowerCase()}://${this.sdkIP}:${this.sdkPort}/${this.sdkChannel}?streamType=${this.sdkStreamType}`;
            }
            if(this.ChannelInfo.Protocol == "ISUP") {
                this.ChannelInfo.Rtsp = `${this.ChannelInfo.Protocol.toLowerCase()}://localhost/${this.isupChannel}?deviceID=${encodeURIComponent(this.isupDeviceID)}&streamType=${this.isupStreamType}`;
            }
            $.get("/api/v1/setchannelconfig", this.getCommitData()).then(data => {
                if ((data.LiveQing || data.NVR).Header.ErrorNum == 200) {
                    this.$message({
                        type: "success",
                        message: "配置成功！"
                    });
                    this.hide();
                    this.$emit("submit");
                } else {
                    this.$message({
                        type: "error",
                        message: "配置失败！"
                    });
                }
            });
        },
        defChannelInfo() {
            return {
                Channel: 0,
                Name: "",
                Enable: 0,
                Protocol: "RTSP",
                Rtsp: "",
                Onvif: "",
                UserName: "",
                Password: "",
                Cdn: "",
                OSD: "",
                GBID: "",
                Audio: "0",
                OnDemand: 0,
                Record: 0,
                Transport: "TCP",
                Longitude: "",
                Latitude: "",
                RequireVideoBitRate: "",
                RequireVideoWidth: "",
                RequireVideoHeight: "",
                Description: "",
            };
        },
        getCommitData() {
            var data = {
                Channel: this.ChannelInfo.Channel,
                Name: this.ChannelInfo.Name,
                Enable: this.ChannelInfo.Enable,
                Protocol: this.ChannelInfo.Protocol,
                RTSP: this.ChannelInfo.Rtsp,
                ONVIF: this.ChannelInfo.Onvif,
                Username: this.ChannelInfo.UserName,
                Password: this.ChannelInfo.Password,
                Cdn: this.ChannelInfo.Cdn,
                OSD: this.ChannelInfo.OSD,
                GBID: this.ChannelInfo.GBID,
                OnDemand: this.ChannelInfo.OnDemand,
                Audio: this.ChannelInfo.Audio,
                Record: this.ChannelInfo.Record,
                Transport: this.ChannelInfo.Transport,
                Longitude: this.ChannelInfo.Longitude,
                Latitude: this.ChannelInfo.Latitude,
                RequireVideoBitRate: this.ChannelInfo.RequireVideoBitRate,
                RequireVideoWidth: this.ChannelInfo.RequireVideoWidth,
                RequireVideoHeight: this.ChannelInfo.RequireVideoHeight,
                Description: this.ChannelInfo.Description,
            };
            if(this.ChannelInfo.Protocol.endsWith("SDK")) {
                data.RTSP = `${this.ChannelInfo.Protocol.toLowerCase()}://${this.sdkIP}:${this.sdkPort}/${this.sdkChannel}?streamType=${this.sdkStreamType}`;
            }
            if(this.ChannelInfo.Protocol == "ISUP") {
                data.RTSP = `${this.ChannelInfo.Protocol.toLowerCase()}://localhost/${this.isupChannel}?deviceID=${encodeURIComponent(this.isupDeviceID)}&streamType=${this.isupStreamType}`;
            }
            return data;
        },
        probe() {
            if(!this.detectIP) {
                this.$message({
                    type: "error",
                    message: "探测ONVIF IP 不能为空"
                })
                return
            }
            $.get("/api/v1/probedevice", {
                ip: this.detectIP,
                username: this.detectUsername,
                password: this.detectPassword
            }).then(data => {
                if ((data.LiveQing || data.NVR).Header.ErrorNum == 200) {
                    var body = (data.LiveQing || data.NVR).Body;
                    if (body) {
                        this.ChannelInfo.UserName = body.UserName;
                        this.ChannelInfo.Password = body.Password;
                        this.ChannelInfo.Rtsp = body.RTSP;
                        this.ChannelInfo.Onvif = body.ONVIF;
                        // this.ChannelInfo.Protocol = "ONVIF";
                        this.$message({
                            type: "success",
                            message: "探测成功!"
                        })
                        return;
                    }
                }
                this.$message({
                    type: "error",
                    message: (data.LiveQing || data.NVR).Header.ErrorString
                })
            })
        },
        discover(queryString, cb) {
            var list = [];
            $.get("/api/v1/discoverdevices").then(data => {
                for(var channel of (data.LiveQing || data.NVR).Body.Channels) {
                    list.push({
                        value: channel.IP
                    });
                }
                list = list.filter(val => {
                    return new RegExp(queryString, "i").test(val.value);
                });
                cb(list);
            });
        },
        isupDevices(queryString, cb) {
            var list = [];
            $.get("/api/v1/isup/devices", {
                q: queryString
            }).then(data => {
                if(data && data.Devices) {
                    for (var dev of data.Devices) {
                        list.push({
                            value: dev.ID,
                            ip: dev.RemoteIP,
                        });
                    }
                }
                cb(list);
            })
        },
        isupChannels(queryString, cb) {
            var list = [];
            $.get("/api/v1/isup/devices", {
                q: this.isupDeviceID
            }).then(data => {
                if(data && data.Devices) {
                    for (var dev of data.Devices) {
                        if(dev.ID == this.isupDeviceID) {
                            var start = dev.ChannelStart || 1;
                            var count = dev.ChannelCount || 0;
                            for(var i = 0; i < count; i++) {
                                list.push({
                                    value: `${start + i}`,
                                })
                            }
                            break;
                        }
                    }
                }
                cb(list);
            })
        },
        listAudio(queryString, cb) {
            var list = [];
            $.get("/api/v1/audio/list", {
                q: queryString
            }).then(data => {
                if(data && data.rows) {
                    for (var val of data.rows) {
                        list.push({
                            value: val
                        });
                    }
                }
                cb(list);
            });
        },
        onUploadAudioSuccess(res, file, fileList) {
            this.bAudioUploading = false;
            this.ChannelInfo.Audio = res;
        },
        onUploadAudioProgress(evt, file, fileList) {
            this.bAudioUploading = true;
        },
        onUploadAudioError(err, file, fileList) {
            this.bAudioUploading = false;
            if (err) {
                this.$message({
                    type: "error",
                    message: err + ""
                })
            }
        },
        onPasteLngLat(e) {
            try {
                var vals = e.clipboardData.getData('Text').trim().split(/\s*,\s*/);
                if(vals.length == 2) {
                    this.ChannelInfo.Longitude = vals[0];
                    this.ChannelInfo.Latitude = vals[1];
                    e.preventDefault();
                }
            } catch (error) {
                console.log(error);
            }
        },
        defSdkPort(sdk) {
            var port = "";
            switch(sdk) {
                case "HIKSDK":
                    port = "8000";
                    break;
                case "DHSDK":
                    port = "37777";
                    break;
                case "TDYSDK":
                    port = "3000";
                    break;
            }
            return port;
        },
    },
    watch: {
        "ChannelInfo.Protocol": function(newVal, oldVal) {
            if(newVal.endsWith("SDK") && (!this.sdkPort || !this.sdkIP)) {
                this.sdkPort = this.defSdkPort(newVal);
            }
            if(newVal == "ISUP") {
                $.ajax({
                    method: "GET",
                    url: "/api/v1/isup/status",
                    global: false,
                }).then(ret => {
                    this.isupEnable = !!ret.Enable;
                    this.isupListen = !!ret.Listen;
                    this.isupStatus = ret.Status || "";
                    this.isupOnlineCount = ret.OnlineCount || 0;
                });
            }
        }
    },
    computed: {
        ...mapState(["serverInfo"]),
        isNoChange() {
            var localeData = JSON.stringify(this.getCommitData());
            return this.origData.localeCompare(localeData) == 0;
        },
        audioReadonly() {
            var audio = this.ChannelInfo["Audio"];
            return audio == "1" || audio == "0";
        },
        showAuth() {
            if(this.bShowMore) return true;
            var ret = true;
            switch(this.ChannelInfo['Protocol']) {
                case "RTMP":
                    ret = false;
                    break;
                case "FLV":
                    ret = false;
                    break;
                case "HLS":
                    ret = false;
                    break;
                case "ISUP":
                    ret = false;
                    break;
                case "FILE":
                    ret = false;
                    break;
            }
            return ret;
        },
        sdkText() {
            var text = "SDK"
            switch(this.ChannelInfo["Protocol"]) {
                case "HIKSDK":
                    text = "海康 SDK";
                    break;
                case "DHSDK":
                    text = "大华 SDK";
                    break;
                case "TDYSDK":
                    text = "天地伟业 SDK";
                    break;
            }
            return text;
        },
        rtspText() {
            var text = "直播流地址";
            switch(this.ChannelInfo["Protocol"]) {
                case "FILE":
                    text = "视频文件路径";
                    break;
            }
            return text;
        },
        audioText() {
            var text = "自定义音频";
            switch(this.ChannelInfo["Audio"]) {
                case "0":
                    text = "静音";
                    break;
                case "1":
                    text = "原始音频";
                    break;
            }
            return text;
        },
        alertMsg() {
            var msg = "";
            if(/(draw_text['"]?\s*=[^\S\r\n]*\S+)|(draw_image['"]?\s*=[^\S\r\n]*\S+)/.test(this.ChannelInfo.OSD)) {
                msg = "叠加水印";
            } else if(this.ChannelInfo.RequireVideoBitRate) {
                msg = "视频码率";
            } else if(this.ChannelInfo.RequireVideoWidth || this.ChannelInfo.RequireVideoHeight) {
                msg = "视频分辨率";
            }
            if(this.ChannelInfo.Protocol == "ISUP" && (!this.isupDeviceID || !msg)) {
                if(!this.isupEnable) return "ISUP 服务未启用, 在【基础配置】>【海康 ISUP 接入配置】中配置启用";
                if(!this.isupListen) {
                    if(this.isupStatus) {
                        return `ISUP 服务监听异常, ${this.isupStatus}`;
                    }
                    return "ISUP 服务未监听";
                }
            }
            if(msg) {
                return `更多配置设置了${msg}，可能带来额外的性能消耗`;
            }
            return msg;
        }
    }
};
</script>

<style lang="less" scoped>
@media screen and(min-width: 992px){
    .modal-dialog.modal-lgg {
        width: 90%;
    }
}

@media screen and(min-width: 1200px){
    .modal-dialog.modal-lgg {
        width: 1200px;
    }
}
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
}
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;    /*outer */
}
</style>

<style lang="less">
.show-list {
    margin-left: 30px;
    margin-top: 4px;
    max-height: 600px;
    overflow-y: auto;

    ul li {
        list-style: none;
        border-left: 1px solid #bbb;
        padding: 12px 0;
        margin-left: -31px;

        &.online {
            color: #bbb;
            cursor: pointer;
        }

        &.offline {
            color: #bbb;
            cursor: default;
        }
    }
}

#audio-uploader {
    .el-upload {
        width: 100%;
        .el-upload-dragger {
            width: 100%;
            height: auto;
            .el-icon-upload {
                margin: 10px;
            }
            .el-upload__text {
                margin-bottom: 10px;
            }
        }
    }
}

#input-onvif-ip.el-input__inner, #input-isup-device-id.el-input__inner, #input-isup-channel.el-input__inner, #input-audio.el-input__inner {
    width: 100%;
    height: 34px;
    line-height: 34px;
}
.has-error .el-input__inner {
    border-color: #a94442;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
</style>
